package cn.kzgg.system.service.impl;

import cn.kzgg.system.domain.Menu;
import cn.kzgg.system.mapper.MenuMapper;
import cn.kzgg.system.service.IMenuService;
import cn.kzgg.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author KZGG
 * @since 2022-06-21
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public List<Menu> tree() {
        //1.先获取所有的Menu
        List<Menu> menus = menuMapper.loadAll();
        //2.为了找出所有menu的父级,将数据转换为map
        Map<Long, Menu> allMenus = menus.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        //3.创建顶级部门对象
        List<Menu> firstMenu = new ArrayList<>();
        for (Menu tmp : menus) {
            //4.如果有哪个menu没有父级id那说明他就是顶级对象
            if(tmp.getParentId()==null){
                //将它存到顶级对象中
                firstMenu.add(tmp);
            }else {
                //5.如果有父亲id那么将自己存到父级的children中
                //5.1首先获得父亲
                Menu parent = allMenus.get(tmp.getParentId());
                //5.2将自己放入父亲的children
                if(parent!=null){
                    parent.getChildren().add(tmp);

                }

            }
        }

        return firstMenu;
    }
}
